﻿using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Windows.Forms;
using Kobets.Automation.Chimera.Common.Contracts;
using Microsoft.Win32;
using Kobets.Automation.Chimera.AgentConfig.Properties;
using Kobets.Automation.Chimera.Common;

namespace Kobets.Automation.Chimera.AgentConfig
{
    public partial class ConfigForm : Form
    {
        public ConfigForm()
        {
            InitializeComponent();

            var suffix = "";
            if (Environment.Is64BitOperatingSystem) suffix = "Wow6432Node";
            var controllerUri = CommonMethods.RegistryRead(Registry.LocalMachine, @"SOFTWARE\" + suffix + @"Kobets\Chimera\Agent", "ControllerUri");
            if (!String.IsNullOrWhiteSpace(controllerUri)) controllerTextbox.Text = controllerUri;
        }

        private void CancelButtonClick(object sender, EventArgs e)
        {
            Hide();
        }

        private void OkButtonClick(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(controllerTextbox.Text))
                MessageBox.Show(MyResources.ConfigForm_OKButtonClick_Please_enter_valid_controller_IP_or_network_name);
            else
            {
                var controllerChannelFactory = new ChannelFactory<IControllerContract>(new BasicHttpContextBinding {SendTimeout = TimeSpan.Parse("00:10:00"), ReceiveTimeout = TimeSpan.Parse("00:10:00")}, "http://" + controllerTextbox.Text + ":8081/chimeracontroller");

                try
                {
                    if (controllerChannelFactory.State != CommunicationState.Opened) controllerChannelFactory.Open();

                    if (controllerChannelFactory.State != CommunicationState.Opened)
                        MessageBox.Show(MyResources.ConfigForm_OKButtonClick_Unable_to_find_controller_or_name_invalid);
                    else
                    {
                        var client = controllerChannelFactory.CreateChannel();
                        var agent = new Agent { Name = Environment.MachineName, NetworkName = CommonMethods.GetLocalhostFqdn(), Controller = client.GetName() };
                        client.RegisterAgent(agent); // register agent with controller

                        if (client.GetAssociatedAgents().Any(n => n.Name == agent.Name))
                        {
                            var identity = EndpointIdentity.CreateDnsIdentity("Chimera");
                            var address = new EndpointAddress(new Uri("http://" + Environment.MachineName + ":8080/chimeraagent"), identity);
                            var agentChannelFactory = new ChannelFactory<IAgentContract>(new CustomHttpBinding(false) { SendTimeout = TimeSpan.Parse("00:10:00"), ReceiveTimeout = TimeSpan.Parse("00:10:00"), MaxMessageSize = 52428800 }, address);
                            agentChannelFactory.Credentials.UserName.UserName = "chimera";
                            agentChannelFactory.Credentials.UserName.Password = "chimera";
                            agentChannelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByIssuerName, "Chimera");

                            if (controllerChannelFactory.State != CommunicationState.Opened) controllerChannelFactory.Open();

                            if (controllerChannelFactory.State != CommunicationState.Opened)
                                MessageBox.Show(MyResources.ConfigForm_OKButtonClick_Unable_to_open_channel_to_local_agent);
                            else
                            {
                                var client2 = agentChannelFactory.CreateChannel();
                                client2.SetController(controllerTextbox.Text); // set controller on the agent
                                
                                var agentDetails = client2.GetSdi();

                                if (agentDetails.Controller == controllerTextbox.Text)
                                {
                                    MessageBox.Show(MyResources.ConfigForm_OKButtonClick_Registration_successful);
                                    Hide();
                                }
                                else
                                    MessageBox.Show(MyResources.ConfigForm_OKButtonClick_Local_agent_didn_t_update_controller_info_);
                            }
                        }
                        else
                            MessageBox.Show(MyResources.ConfigForm_OKButtonClick_Error__Unable_to_register_agent,
                                            MyResources.ConfigForm_OKButtonClick_Error, MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, MyResources.ConfigForm_OKButtonClick_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}
